#include "inputwidget.h"
#include "ui_inputwidget.h"
#include<QDateTime>

InputWidget::InputWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::InputWidget)
{
    ui->setupUi(this);

    //初始化widget
    setWindowFlags(windowFlags()&~Qt::WindowMaximizeButtonHint);
    //固定窗口大小
    setFixedSize(width(),height());
    //光标定位
    ui->lineEdit->setFocus();

    //初始化 combox
    QSqlQuery sqlResult;

    QString sqlQuery = "select stock_id from commodity_data";
    sqlResult.exec(sqlQuery);
    int i = 0;
    while(sqlResult.next())
    {
        //addItem()加在末尾 , insertItem() 指定加在某个位置
        ui->comboBox->addItem(sqlResult.value(0).toString());
        i++;
    }
}

InputWidget::~InputWidget()
{
    delete ui;
}

void InputWidget::closeEvent(QCloseEvent *event)
{
    emit windowClosed();
    QWidget::closeEvent(event);
}


//商品入库
void InputWidget::on_pushButton_comStore_clicked()
{
    QSqlDatabase db = QSqlDatabase::database();
    if(!db.transaction())
    {
        return;
    }
    QSqlQuery sqlResult;
    try {
        QString storeCount = ui->lineEdit->text();
        QString storeTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
        QString storeId = ui->comboBox->currentText();
        QString sqlUpdate = QString("update commodity_data"
                                    " set stock_amount=stock_amount+%1,store_time='%2' where stock_id = %3").arg(storeCount).arg(storeTime).arg(storeId);
        qDebug() << sqlUpdate;
        if(sqlResult.exec(sqlUpdate))
        {
            QMessageBox::information(this,"成功","恭喜你,商品入库成功!");
            //同时将数据插入到汇总入库表
            //商品编号 商品名称 商品入库数量 商品数量 入库时间
            QString sqlQuery = QString("select stock_name,stock_amount from commodity_data where stock_id = %1").arg(storeId);
            sqlResult.exec(sqlQuery);
            QString storeName,allCount;
            sqlResult.next();
            storeName = sqlResult.value(0).toString();
            allCount = sqlResult.value(1).toString();

            //商品编号 商品名称 商品入库数量 商品数量 入库时间
            QString sqlStoreCom = QString("insert into commodity_store"
                                          " values (%1,'%2',%3,'%4','%5')").arg(storeId).arg(storeName).arg(storeCount).arg(allCount).arg(storeTime);
            qDebug() << sqlStoreCom;
            if(!sqlResult.exec(sqlStoreCom))
            {
                QMessageBox::information(this,"失败","输入插入到汇总入库表失败!");
                 throw std::runtime_error("输入插入到汇总入库表失败!");
            }


        }
        else
        {
            QMessageBox::critical(this,"警告","商品入库失败,请重新检查...");
            throw std::runtime_error("商品入库失败,请重新检查...");
            return;
        }

        db.commit();

    } catch (...) {
        db.rollback();
        return;
    }

}



//退出操作
void InputWidget::on_pushButton_exit_clicked()
{
    this->close();
}
